import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import dayjs from 'dayjs'
export function useWindowScroll() {
  const x = ref(0)
  const y = ref(0)
  const onScroll = () => {
    x.value = document.documentElement.scrollLeft
    y.value = document.documentElement.scrollTop
  }
  onMounted(() => {
    window.addEventListener('scroll', onScroll)
  })
  onBeforeUnmount(() => {
    window.removeEventListener('scroll', onScroll)
  })
  return {
    x,
    y
  }
}

/**
 *
 * @param {*} apiFn 是一个用于发送请求的函数
 * @returns target: 绑定DOM  list: 请求的数据
 */
export function useLazyData(apiFn) {
  const target = ref(null)
  const list = ref([])
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        // 在可视区
        stop()
        // 发送请求获取数据
        apiFn().then(res => {
          list.value = res.result
          // console.log(res)
        })
      }
    },
    {
      threshold: 0
    }
  )
  return {
    target,
    list
  }
}

// 倒计时的封装
export function useCounter(num = 60) {
  const time = ref(0)
  const { pause, resume } = useIntervalFn(
    () => {
      time.value--
      if (time.value === 0) {
        pause()
      }
    },
    1000,
    {
      immediate: false
    }
  )
  const start = () => {
    time.value = num
    resume()
  }

  onBeforeUnmount(() => {
    pause()
  })
  return {
    time,
    start
  }
}

/**
 * 封装支付倒计时
 * @returns
 */
export function usePayTime() {
  const time = ref(0)
  const showTime = ref('')
  const { resume, pause } = useIntervalFn(
    () => {
      time.value--
      showTime.value = dayjs.unix(time.value).format('mm分ss秒')
      if (time.value <= 0) {
        pause()
      }
    },
    1000,
    {
      immediate: false
    }
  )

  onBeforeUnmount(() => {
    pause()
  })
  const start = (num = 0) => {
    time.value = num
    // console.log(num)
    showTime.value = dayjs.unix(time.value).format('mm分ss秒')
    resume()
  }
  return {
    start,
    time,
    showTime
  }
}
